package com.example.xlmkotlinwanandroid.ui.activity

import android.os.Bundle
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProviders
import com.example.xlmkotlinwanandroid.R
import com.example.xlmkotlinwanandroid.base.BaseActivity
import com.example.xlmkotlinwanandroid.databinding.ActivityMainBinding
import com.example.xlmkotlinwanandroid.model.viewmodel.HomeViewModel
import com.example.xlmkotlinwanandroid.ui.fragment.*
import com.example.xlmkotlinwanandroid.ui.fragment.square.SquareFragment


class MainActivity : BaseActivity() {

    private lateinit var mainBinding: ActivityMainBinding

    //注意该处bylazy可以挂在所有有返回值的东西，这个地方是延迟初始化，提升性能
    //该处的意思是要对mFragments进行延迟初始化，初始化之后返回一个list<Fragment>
    private val mFragments by lazy {
        arrayListOf(
            HomeFragment(),
            ProjectFragment(),
            SquareFragment(),
            OfficalAccountFragment(),
            MineFragment()
        )
    }

    private var preFragment: Fragment? = null
    private var curFragment: Fragment = mFragments[0]
    private val homeViewModel: HomeViewModel by lazy {
        ViewModelProviders.of(this).get(HomeViewModel::class.java)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initView()
    }


    override fun initView() {
        mainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
        //注意该处ASM精简的写法
        //监听的接口只有一个方法，可以用ASM，
        // 这个方法有一个参数，需要左侧带上参数，否则报错很多，
        mainBinding.bnvRoot.setOnNavigationItemSelectedListener { item ->
            onTabItemSelected(item.itemId)
            true
        }
        //需要默认选中一个
        onTabItemSelected(R.id.menu_home)
    }

    private fun onTabItemSelected(id: Int) {
        when (id) {
            R.id.menu_home -> curFragment = mFragments[0]
            R.id.menu_project -> curFragment = mFragments[1]
            R.id.menu_square -> curFragment = mFragments[2]
            R.id.menu_offical_account -> curFragment = mFragments[3]
            R.id.menu_me -> curFragment = mFragments[4]
        }
        if (!curFragment.isAdded) {
            supportFragmentManager.beginTransaction().add(R.id.fl_root, curFragment)
                .show(curFragment)
                .commit()
        } else {
            supportFragmentManager.beginTransaction().show(curFragment).commit()
        }

        if (preFragment != null && preFragment != curFragment && preFragment!!.isAdded) {
            supportFragmentManager.beginTransaction().hide(preFragment!!).commit()
        }

        preFragment = curFragment
    }
}